package com.nulldev.util.net.experimental.groupedudp.files;

import java.io.File;
import java.io.IOException;
import java.net.InetAddress;
import java.util.Arrays;

import com.nulldev.util.io.FileUtil;
import com.nulldev.util.net.experimental.groupedudp.AGroupThread;
import com.nulldev.util.net.experimental.groupedudp.Encryptor;
import com.nulldev.util.net.experimental.groupedudp.UDPException;
import com.nulldev.util.net.experimental.groupedudp.datagrams.ADatagram;
import com.nulldev.util.net.experimental.groupedudp.datagrams.files.FileSharePartRequest;
import com.nulldev.util.other.ArrayUtils;

public class ReceivedTextFile extends AReceivedFile<String> {
	private final String[] parts;

    /**
     *
     * @param name Unique name of file
     * @param parts Count of fileParts to receive
     * @param client Thread with socket, which can SharedFile use for
     * CLIENT_FILE_SHARE_PART_REQUEST
     * @param encryptor object responsible for encrypting requests
     * @param server server ip
     */
    public ReceivedTextFile(String name, int parts, AGroupThread client, Encryptor encryptor, InetAddress server) {
        super(name, client, encryptor, server);
        this.parts = new String[parts];
    }
    
    @Override
    public void setPart(int index, String content) {
        parts[index] = content;
    }

    @Override
    protected boolean finishOrRequest() {
        for (int i = 0; i < parts.length; i++) {
            if (parts[i] == null) {
                ADatagram datagram = new FileSharePartRequest(encryptor, name, i);
                client.sendDatagram(source, datagram);
                return false;
            }
        }
        return true;
    }

    @Override
    protected void fillFile(File createdFile) throws IOException {
    	if (!createdFile.exists()) {
    		if (!createdFile.createNewFile()) {
    			throw new IOException("Unable to create file!");
    		}
    	}
        try{
            FileUtil.writeFile(createdFile, ArrayUtils.toArrayList(this.parts));
        }catch(Exception e){
            throw new UDPException("Failed to save text file: ", e);
        }
    }
    
    @Override
    public boolean isPartValid(String data, int checksum) {
        return SharedTextFile.getChecksum(data)==checksum;
    }
}
